package net.pingfang.devicelock.Decoder;


import lombok.extern.slf4j.Slf4j;
import net.pingfang.devicelock.common.ParamCommon;
import org.springframework.integration.ip.tcp.serializer.AbstractByteArraySerializer;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

@Slf4j
public class HHDLockSerializer extends AbstractByteArraySerializer  {

    /*
        解封失败，电子锁不在线
        7B 5A 43 4E 48 44 00 00 21 50 44 19 41 FF FF FF FF FF FF FF FF FF FF FF FF FF FF
        FF FF FF FF FF FF FF FF FF FF EA 0E
        开头是7B结尾不确定
        施封失败，电子锁不在线
        7B 5A 43 4E 48 44 00 00 21 50 42 0F 21 FF FF FF FF FF FF FF FF FF FF FF FF FF FF 71 A4
     */


    private static final byte BeginSIGN = 0x7B;

    @Override
    public byte[] deserialize(InputStream inputStream)  {

        try{
            log.info("收到回传值:{}",inputStream.read());
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            int currentByte;
            boolean Sign = false;
            // 16进制接收
            while ((currentByte = inputStream.read()) != -1) {
                log.info("======={}",currentByte);
                if (currentByte == BeginSIGN ) {
                    Sign = true;
                }else if(Sign){
                    buffer.write(currentByte);
                }

            }
            return buffer.toByteArray(); // 返回完整报文（含7E）
        }catch (IOException e){
            log.error("在接收TCP报文时发生分隔符异常，{}",e.getMessage());
        }
        return null;
    }

    @Override
    public void serialize(byte[] bytes, OutputStream outputStream) throws IOException {
        outputStream.write(bytes);
    }
}
